package com.myblog.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.myblog.constant.CodeType;
import com.myblog.mapper.RewardMapper;
import com.myblog.model.Reward;
import com.myblog.service.RewardService;
import com.myblog.utils.DataMap;
import com.myblog.utils.FileUtilToLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class RewardServiceImpl implements RewardService {

    @Autowired
    private RewardMapper rewardMapper;

    @Override
    public DataMap getReward() {
        List<Reward> rewards = rewardMapper.selectAllReward();

        List<JSONObject> result = new ArrayList<>();
        for (Reward reward : rewards) {
            JSONObject rewardJson = new JSONObject();
            rewardJson.put("id",reward.getId());
            rewardJson.put("fundRaiser",reward.getFundRaiser());
            rewardJson.put("rewardMoney",reward.getRewardMoney());
            rewardJson.put("fundRaisingSources",reward.getFundRaisingSources());
            rewardJson.put("fundraisingPlace",reward.getFundraisingPlace());
            rewardJson.put("remarks",reward.getRemarks());
            rewardJson.put("rewardDate",reward.getRewardDate());
            result.add(rewardJson);
        }

        return DataMap.success().setData(result);
    }

    @Override
    public DataMap deleteRewardById(Integer id) {
        rewardMapper.deleteRewardById(id);
        return DataMap.success(CodeType.DELETE_REWARD_SUCCESS);
    }

    @Override
    public DataMap addReward(MultipartFile file,Reward reward) {
        //上传本地
        String fileUrl = null;
        try {
            fileUrl = FileUtilToLocal.uploadToLocal(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

//        //上传华为云服务器
//        FileUtil fileUtil = new FileUtil();
//        //获取文件路径
//        String filePath = this.getClass().getResource("/").getPath().substring(1) + "blogImg/";
//        //获取文件类型
//        String contentType = file.getContentType();
//        //获取文件类型名称
//        String fileEx = contentType.substring(contentType.indexOf("/") + 1);
//        TimeUtil timeUtil = new TimeUtil();
//        //文件名
//        String filename = timeUtil.getLongTime()+"."+fileEx;
//        //获取证书
//        String fileCatalog = "rewardRecord" +timeUtil.getLongTime();
//        String fileUrl = fileUtil.uploadFile(fileUtil.multipartFileToFile(file, filePath, filename), fileCatalog);


        reward.setRewardUrl(fileUrl);
        rewardMapper.insertReward(reward);
        return DataMap.success(CodeType.ADD_REWARD_SUCCESS);
    }
}
